package com.woniu.darryringmall.admin.jwt;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class JwtRealm  extends AuthorizingRealm {
    @Autowired
    private Audience audience;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken t = (JwtToken) token;
        String jwt = t.getPrincipal().toString();
        boolean isValid = JwtUtil.parseJwt(jwt, audience.getBase64Secret()); //校验jwt
        if (isValid)
            return new SimpleAuthenticationInfo(jwt, jwt, getName());
        else
            throw new AuthenticationException("JWT解析出错");
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
